<?php

/**
 * 自动更新节点
 * @author zsoner <[zsoner@wsxhr.com]>
 */
class AutoNode extends ControllerAdmin
{
    public function index()
    {
        $this->update();
        json(1,'更新成功！');
    }

    /**
     * 执行更新节点操作
     * @return void
     */
    public function update()
    {
        //清空表

        db()->execute('truncate table auth_rule');
        foreach ($this->nodes as $key => $actions) {
            $data = ['type' => 0, 'name' => $key, 'code' => $this->code($key)];
            db('auth_rule')->add($data);
            $insert_id = db()->getLastInsID();
            $this->insertNodes($insert_id, $key, $actions);
        }
    }

    /**
     * 插入子节点
     * @param  [int] $insert_id    父ID
     * @param  [string] $calss     [所属类]
     * @param  [string] $actions   [当前方法]
     * @return void
     */
    public function insertNodes($insert_id, $calss, $actions)
    {
        foreach ($actions as $key => $value) {
            $data = ['pid' => $insert_id, 'name' => $calss . '/' . $value, 'title' => $this->getTitle($value), 'code' => $key];
            db('auth_rule')->add($data);
        }
    }


    protected function getTitle($name)
    {   
        $file=APP_PATH.'config'.DIRECTORY_SEPARATOR.'auto_replace.php';

        if(file_exists($file)){
            $preg_user=include($file);
        }

        $preg_default=array(
                'system'=>'系统',
                'auth'=>'认证',
                'credit'=>'信用卡',
                'account'=>'账户',
                'logs'=>'日志',
                'log'=>'日志',
                'setSettings'=>'设置',
                'navigation'=>'导航',
                'upload'=>'上传',
                'feedback'=>'反馈',
                'company'=>'公司',
                'rebates'=>'回扣',
                'rebate'=>'回扣',
                'rule'=>'规则',
                'rules'=>'规则',
                'refresh'=>'更新',
                'node'=>'节点',
                'addresses'=>'地址',
                'switch'=>'切换',
                'online'=>'在线',
                'ubscribe'=>'订阅',
                'comment'=>'评论',
                'count'=>'数目',
                'hotsale'=>'热销',
                'sale'=>'销售',
                'check'=>'检查',
                'send'=>'发送',
                'verifed'=>'已验证',
                'unverifed'=>'未验证',
                'exports'=>'导出',
                'page'=>'页',
                'clone'=>'克隆',
                'cloud'=>'云',
                'balance'=>'流水',
                'wechat'=>'微信',
                'update'=>'更新',
                'index' => '查看列表',
                'addTo' => '加入',
                'add' => '新增',
                'edit' => '编辑',
                'deleted'=>'已删除',
                'delete' => '删除',
                'listall'=>'列出所有',
                'list' => '列表',
                'gets' => '获取',
                'get' => '获取',
                'contact' => '联系方式',
                'item' => '子项目',
                'group' => '组',
                'user' => '用户',
                'from' => '从',
                'allot' => '分配',
                'access' => '权限',
                'status' => '状态',
                'generate'=>'生成',
                'static'=>'静态',
                'comfirm'=>'确认',
                'ExpTemplate'=>'物流模板',
                'clear'=>'清除',
                'change' => '改变',
                'response'=>'回复',
                'history'=>'历史',
                'replys'=>'回复',
                'reply'=>'回复',
                'goods' => '产品', 
                'class' => '分类', 
                'specs' => '规格',
                'spec' => '规格',
                'brand' => '品牌',
                'cancel' => '取消',
                'detail' => '详情',
                'express'=>'物流',
                'refund'=>'退款',
                'payed'=>'已支付',
                'load'=>'加载',
                'orderstat'=> '订单',
                'orders' => '订单',
                'order' => '订单',
                'instock'=>'库存',
                'stock'=>'库存',
                'category'=>'分类',
                'alter'=>'弹出',
                'message'=>'消息',
                'iframe'=>'框架',
                'settings'=>'设置',
                'set'=>'设置',
                'remove'=>'删除',
                'del'=>'删除',
                'create'=>'新增',
                'info'=>'信息',
                'level'=>'级别',
                'image'=>'图片',
                'products'=>'产品',
                'product'=>'产品',
                'percent'=>'所占比',
                'customers'=>'用户',
                'customer'=>'用户',
                'dcount'=>'折扣',
                'gmess'=>'素材',
                'ajax'=>'动态',
                'record'=>'记录',
                'modify'=>'修改',
                'modi'=>'修改',
                'menu'=>'菜单',
                'manage'=>'管理',
                'banner'=>'广告图',
                'select'=>'选择',
                'nums'=>'数目',
                'stat'=>'信息',
                'data'=>'数据',
                'save'=>'保存',
                'serials'=>'系列',
                'serial'=>'系列',
                'envs'=>'红包',
                'env'=>'红包',
                'auto'=>'自动',
                'to' => '到',
                'bind'=>'绑定',
                'by'=>'通过',
                '_'=>''
            );
     
        $preg=$preg_default+$preg_user;

        foreach ($preg as $key => $value) {
            $name = str_replace(strtolower($key), $value,strtolower($name));
        }
        return $name;
    }


    public function __construct()
    {
        $arr = glob(__DIR__ . DIRECTORY_SEPARATOR . '*.php');

        $Nodes = array();
        foreach ($arr as $path) {
            $basename = basename($path, '.php');
            //仅支持合法的命名
            if (preg_match('/^\\w+$/', $basename) && $path != __FILE__) {
                //require $path;
                $className = $basename;
                $ref = new \ReflectionClass($className);
                foreach ($ref->getMethods() as $key => $methods) {
                    if ($this->notClass($methods->class) && $methods->isPublic() && $this->notFuc($methods->name)) {
                        $key = $this->code($methods->class . '/' . $methods->getName());
                        $Nodes[$this->getIndexName($methods->class)][$key] = $methods->getName();
                    }
                }
            }
        }
        
        $this->nodes = $Nodes;
    }
    protected function notFuc($name)
    {
        return !in_array($name, ['__construct', '__destruct', 'show', 'assign', '__set', 'get', '__get', '__isset', '__call', 'getInt', 'getStr', 'getPostFloat', 'getPostInt', 'getPostStr', 'getRequestHash', 'isAjax', 'getUploadedFiles', 'hasFiles', 'getShopname', 'beforeLoad', 'log', 'getCompanyId', 'getUid', 'getBaseURI', 'getSetting', 'modulePreload', 'show', 'isCached', 'loadModel', 'inWechat', 'getOpenId', 'add_include_path', 'getIp', 'echoJson', 'echoJsonRaw', 'echoText', 'echoFail', 'echoSuccess', 'echoMsg', 'toJson', 'initSettings', '_getSettings', 'pGet', 'pPost', 'pCookie', 'sCookie', 'sCookieHttpOnly', 'getpostV', 'server', 'post', 'unIescape', 'redirect']);
    }
    protected function notClass($name)
    {   
        return !in_array($name, ['wCommon','Wdmin','wTest','WdminAjax']);
    }
    protected function getIndexName($name)
    {
        return $name;
    }
    protected function code62($x)
    {
        $show = '';
        while ($x > 0) {
            $s = $x % 62;
            if ($s > 35) {
                $s = chr($s + 61);
            } elseif ($s > 9 && $s <= 35) {
                $s = chr($s + 55);
            }
            $show .= $s;
            $x = floor($x / 62);
        }
        return $show;
    }

    /**
     * 生成节点唯一对应码
     */
    protected function code($url)
    {
        $url = crc32($url);
        $result = sprintf("%u", $url);
        return $this->code62($result);
    }
}